/*
 * WindVane.c
 *
 * Created: 20/02/2012 14:42:22
 *  Author: Dani
 */ 

#include <avr/io.h>
#include <avr/interrupt.h>

int measure[14];

int ReadWindDirection()
{	
	int WindDirection = 0;
	unsigned char i;
	
	for (i = 1; i < 15; i++)
	{
		WindDirection += measure[i];
	}
	WindDirection = WindDirection*360/1024/14;
	return WindDirection;	
}


void InitVane()
{
	// Conversion every 71 ms.
	
	//------------------------------- ADC -------------------------
	// PA pins are inputs (ADC)
	DDRA = 0;
	// Internal 5 volt reference, ADLAR = 0, Input = ADC0 single ended
	ADMUX = 0b01000000;
	// ADC enable
	// ADC interrupt ENABLED
	// OBS: Bit ADATE = 1 => "Auto triggering" enabled.
	// ADC prescaler = 32 (=> ADC clock = 3,6864 MHz / 32 = 115 kHZ)
	ADCSRA = 0b10101101;
	// "Trigger Source" = "Timer 0 overflow"
	SFIOR = 0b10000000;
  
  
	// ------------------------ Timer 0 -----------------
	// Normal mode, clock prescaler PS = 1024
	TCCR0 = 0b00000101;
	// 14,1 overflows per second
	// 3686400/1024/256 = 14,1
	// Enable Timer0 overflow interrupt
	TIMSK |= 0b00000001;
	
	sei();
}

ISR (ADC_vect)
{
	unsigned char i;
	for (i = 1; i < 14; i++)
	{
		measure[i+1] = measure[i];
	}
	measure[1] = ADCW;
}	